//
//  QuestionDetailViewController.m
//  MingShi
//
//  Created by MJiao on 15/6/27.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "QuestionDetailViewController.h"

#import "UIImageView+AFNetworking.h"
#import "MJRefresh.h"
#import "ImgeUtil.h"
#import "ViewImageScaleViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "QuestionAnswerTableViewCell.h"
#import "UserManager.h"
#import "KVNProgress.h"
#import "QuestionAnswer.h"
#import "QuestionAnswerPageModel.h"
#import "CommonUtils.h"
#import "PostAnswerViewController.h"
#import "ProfileViewController.h"

@interface TmpLaber : UILabel

@end


@implementation TmpLaber

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}

- (CGRect)frame
{
    return super.frame;
}


@end


@interface NSNotificationCenter (UniqueNotif)

- (void)addUniqueObserver:(id)observer selector:(SEL)selector name:(NSString *)name object:(id)object;

@end

@implementation NSNotificationCenter (UniqueNotif)
- (void)addUniqueObserver:(id)observer selector:(SEL)selector name:(NSString *)name object:(id)object {

    [[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];
    [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];

}
@end



@interface QuestionDetailViewController ()
- (void)tapDetected;

/** 用来显示的假数据 */
@property(strong, nonatomic) QuestionAnswerPageModel *questionAnswerPageModel;
@property(strong, nonatomic) NSMutableDictionary *rowHeightDictionary;

@end

@implementation QuestionDetailViewController

- (void)tapDetected {
    self.willViewImageUrl = self.question.imageUrl;
    self.viewViewSmallImgeUrl = self.question.resizedImageUrl;
    [self performSegueWithIdentifier:@"ViewImageIdentifier" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"ViewImageIdentifier"]) {
        ViewImageScaleViewController *destination = segue.destinationViewController;
        //传递参数
        [destination setImageUrl:self.willViewImageUrl];
        [destination setSmallImageUrl:self.viewViewSmallImgeUrl];
    } else if ([segue.identifier isEqualToString:@"ToPostAnswerSegue"]) {
        PostAnswerViewController *destination = segue.destinationViewController;
        [destination setHelpId:self.question.questionId];;
    }
}

- (void)recvRefreshFalg:(NSNotification *)notification {
    self.refreshFalg = YES;
}

//查看答案的图片
- (void)recvViewAnswerImage:(NSNotification *)notification {
    NSString *answerImageUrl = [notification.userInfo objectForKey:@"answerImageUrl"];
    NSString *answerResizeImageUrl = [notification.userInfo objectForKey:@"answerResizeImageUrl"];
    self.willViewImageUrl = answerImageUrl;
    self.viewViewSmallImgeUrl = answerResizeImageUrl;
    [self performSegueWithIdentifier:@"ViewImageIdentifier" sender:self];
}


- (void)recvAppceptAnserAction:(NSNotification *)notification {


    NSInteger answerId = [[notification.userInfo objectForKey:@"answerId"] intValue];

    NSLog(@"recvAppceptAnserAction:%ld", answerId);


    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    [KVNProgress showWithStatus:@"请求中..."];


    // NSInteger userId = [[UserManager shareUserManager] curUser].userId;
    NSInteger Id = self.question.questionId;
    NSInteger Ids = answerId;


    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/help/setok?Id=%ld&Ids=%ld", Id, Ids];

    NSLog(@"urlString:%@", urlString);
    [manager POST:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [KVNProgress dismiss];
        NSString *code = [responseObject objectForKey:@"code"];
        NSLog(@">>>>>>执行到这儿了:%@", code);
        if ([code isEqualToString:@"00"]) {
            //标记问题为已经解决
            self.question.status = @"1";
            //  self.question.replyCount = self.question.replyCount+1;

            [self refreshQuestionStatus];
            [KVNProgress showSuccessWithStatus:[responseObject objectForKey:@"msg"] completion:^{
                NSLog(@">>>>>>执行到这儿了>>>>>>>>>>>>>>>>>>");

            }];
            //重新刷新数据
            [self.scollView.header beginRefreshing];

        } else {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
        }

    }     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [KVNProgress showErrorWithStatus:@"网络异常,请重试"];
    }];


}


- (instancetype)init {
    self = [super init];
    if (self) {
        NSLog(@"init........");
    }

    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 140.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    // [self.scollView setContentSize:CGSizeMake(self.scollView.contentSize.width, 2000)];
    // [self.scollView layoutIfNeeded];
    // [self.scollView updateConstraintsIfNeeded];

    /**
    *  初始化数据集
    */
    if (!self.questionAnswerPageModel) {
        self.questionAnswerPageModel = [[QuestionAnswerPageModel alloc] init];
        self.questionAnswerPageModel.dataArray = [[NSMutableArray alloc] init];
    }

    if (self.question.userId == [[UserManager shareUserManager] curUser].userId) {
        [self.btnFollow setHidden:YES];
    } else {
        self.navigationItem.rightBarButtonItem = nil;
        //       [self.btnDeleteQuestion setHidden:YES];
    }


    // Do any additional setup after loading the view.
    /**
    *  在一个VC里如果第一个控件是UIScrollView，注意是第一个控件，就是首先addsubview在VC.view上。接着加到scrollView上的View就会在Y点上发生64的偏移（也就是navigationBar的高度44+电池条的高度20）。
    这个在iOS7以后才会出现。

    解决办法：
    self.automaticallyAdjustsScrollViewInsets = false; （这是swift）OC类同，self是你当前那个VC。

    如果这个scrollView不是第一个加到self.view上的。也不会发生64的偏移
    */
    self.automaticallyAdjustsScrollViewInsets = false;

    //    self.scollView.contentSize = CGSizeMake(self.scollView.frame.size.width,self.scollView.contentSize.height);

    //    禁止UIScrollView水平方向滚动，只允许垂直方向滚动
    //CGSizeMake(CGFloat width, CGFloat height)
    //self.scollView.contentSize = CGSizeMake(0, self.scollView.frame.size.height);


    NSString *contents = [NSString stringWithFormat:@"问题:%@", self.question.contents];
    contents = [NSString stringWithFormat:@"%@", self.question.contents];

    [self.lbContents setText:contents];

    NSString *nickName = [CommonUtils serializableIdObject:self.question.userName defaultValue:@"昵称"];
    [NSString stringWithFormat:@"昵称:%@", nickName];

    [self.lbQuestionNickName setText:nickName];

    NSString *sex = self.question.sex;

    [self refreshQuestionStatus];

    NSString *gradeName = [CommonUtils serializableIdObject:self.question.gradeName defaultValue:@""];
    NSString *subjectName = [CommonUtils serializableIdObject:self.question.subjectName defaultValue:@""];
    [self.lbGradeName setText:gradeName];
    [self.lbSubjectName setText:subjectName];

    if ([sex isEqualToString:@"男"]) {
        [self.ivSexFlag setImage:[UIImage imageNamed:@"male"]];
    } else if ([sex isEqualToString:@"女"]) {
        [self.ivSexFlag setImage:[UIImage imageNamed:@"female"]];
    } else {
        [self.ivSexFlag setHighlighted:YES];
    }


    NSString *createTime = self.question.createTime;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:SS"];
    @try {
        createTime = [CommonUtils compareCurrentTime:[dateFormat dateFromString:self.question.createTime]];
    }
    @catch (NSException *exception1) {
        NSLog(@"Exception occurred: %@, %@", exception1, [exception1 userInfo]);
    }
    [self.lbPostTime setText:createTime];

    [self.lbQuestionSex setText:sex];

    NSString *sign = [NSString stringWithFormat:@"签名:%@", self.question.slogins];

    [self.lbQuestionSign setText:sign];

    NSURL *imageViewAvatarURL = [NSURL URLWithString:[CommonUtils serializableIdObject:self.question.userImage defaultValue:@""]];
    //圆角
    self.ivAvatar.layer.masksToBounds = YES;
    self.ivAvatar.layer.cornerRadius = 27.5;

    //头像
    [self.ivAvatar setImageWithURL:imageViewAvatarURL placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];

    self.singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
    self.singleTap.numberOfTapsRequired = 1;

    [self.ivQuestionImage setUserInteractionEnabled:YES];
    [self.ivQuestionImage addGestureRecognizer:self.singleTap];

//
    if (self.question.imageUrl) {
        NSURL *imgURL = [NSURL URLWithString:self.question.resizedImageUrl];
        [self.ivQuestionImage setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"loading"]];


        float frameWidth = self.ivQuestionImage.frame.size.width;
        float frmameHeight = (frameWidth * self.question.resizedImageHeight) / self.question.resizedImageWidth;

        self.questionImageLayoutConstraint.constant = frmameHeight;

        [self.view setNeedsLayout]; //更新视图
        [self.view layoutIfNeeded];



    }

    //BOOL isLogined = [[UserManager shareUserManager] curUser].userId != -1;
    /**
    * 表示为自己发布的问题
    */
    if ([self.question.isgood isEqualToString:@"-1"]) {
        [self.btnFollow setHidden:YES];
    }
        /**
        *   陌生人(并且只要已经登陆后才能)
        */
    else if ([self.question.isgood isEqualToString:@"0"]) {
        [self.btnFollow setHidden:NO];
    }
    else {
        [self.btnFollow setHidden:YES];
    }

    /**
    * 对服务器的isgood参数进行容错，按照协定自己发布的消息，isGood应该为-1，但服务器返回为0
    */
    if (self.question.userId == [[UserManager shareUserManager] curUser].userId) {
        [self.btnFollow setHidden:YES];
    }
    /**
    * 已关注
    */
    //    else if ([self.question.isgood isEqualToString:@"1"]) {
    ////        self.btnFollow
    //    }
    //        /**
    //        *   2 表示被关注
    //        */
    //    else if ([self.question.isgood isEqualToString:@"2"]) {
    //
    //    }
    
    //================================================

    //第一次数据加载之前先关闭
    //[self.contentView setHidden:YES];

    self.scollView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{


        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

        NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api//answer/quranswer?helpId=%ld&currentPage=1", (unsigned long) self.question.questionId];

        NSLog(@"urlString:%@", urlString);

        [manager POST:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

            // 结束刷新
            [self.scollView.header endRefreshing];

            [self.questionAnswerPageModel.dataArray removeAllObjects];

            //   NSLog(@"responseObject:%@",responseObject);

            // NSString *code = [responseObject objectForKey:@"code"];
            //   if ([code isEqualToString:@"00"]) {


            @try {
                NSArray *result = [responseObject objectForKey:@"result"];

                [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

                    NSInteger userId = [[obj objectForKey:@"userId"] integerValue];
                    NSInteger answerId = [[obj objectForKey:@"id"] integerValue];

                    NSString *userName = [obj objectForKey:@"userName"];

                    NSString *contents = [obj objectForKey:@"contents"];
                    NSString *status = [obj objectForKey:@"status"];
                    NSString *createTime = [obj objectForKey:@"createtime"];
                    NSString *imageUrl = [obj objectForKey:@"imageUrl"];
                    NSString *resizedImageUrl = [obj objectForKey:@"resizedImageUrl"];
                    NSString *sex = [obj objectForKey:@"sex"];
                    NSString *userImage = [obj objectForKey:@"userImage"];

                    QuestionAnswer *questionAnswer = [[QuestionAnswer alloc] init];

                    questionAnswer.userId = userId;
                    questionAnswer.answerId = answerId;
                    questionAnswer.userName = userName;
                    questionAnswer.contents = contents;
                    questionAnswer.status = status;
                    questionAnswer.createtime = createTime;
                    questionAnswer.imageUrl = imageUrl;
                    questionAnswer.resizedImageUrl = resizedImageUrl;
                    questionAnswer.sex = sex;
                    questionAnswer.userImage = userImage;

                    @try {
                        NSInteger resizedImageHeight = [[obj objectForKey:@"resizedImageHeight"] integerValue];
                        questionAnswer.resizedImageHeight = resizedImageHeight;
                    }
                    @catch (NSException *exception) {
                        NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
                    }

                    @try {
                        NSInteger resizedImageWidth = [[obj objectForKey:@"resizedImageWidth"] integerValue];
                        questionAnswer.resizedImageWidth = resizedImageWidth;
                    }
                    @catch (NSException *exception1) {
                        NSLog(@"Exception occurred: %@, %@", exception1, [exception1 userInfo]);
                    }
                    
                    
                    [self.questionAnswerPageModel.dataArray addObject:questionAnswer];
                }];

                self.question.replyCount = [self.questionAnswerPageModel.dataArray count];
                [self refreshQuestionStatus];


                [self.tableView reloadData];
//
                [UIView setAnimationsEnabled:NO];
                [self.tableView beginUpdates];
//               // [self.scollView setContentSize:CGSizeMake(self.scollView.contentSize.width,self.scollView.contentSize.height)];
                [self.tableView endUpdates];
                [UIView setAnimationsEnabled:YES];

                [self.tableView reloadData];

            }
            @catch (NSException *exception) {
                NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
            }
            // }


        }     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);

            // 结束刷新
            [self.scollView.header endRefreshing];
        }];


        // 进入刷新状态后会自动调用这个block
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.scollView.header.autoChangeAlpha = YES;

    // 马上进入刷新状态
    [self.scollView.header beginRefreshing];

}

- (void)refreshQuestionStatus {
    NSString *status = @"待解决";
    /**
    *  status: 0表示待解决,1表示已解决
    */
    if ([self.question.status isEqualToString:@"0"]) {
        status = @"待解决";
        [self.lbStatusFlag setImage:[UIImage imageNamed:@"usercard_list_ask"]];
    } else if ([self.question.status isEqualToString:@"1"]) {
        status = @"已解决";
        [self.lbStatusFlag setImage:[UIImage imageNamed:@"vote_has_voted"]];
        // [self.btnPostAnswer setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    [self.lbStatus setText:status];
    [self.lbReplyCount setText:[NSString stringWithFormat:@"%ld回复", self.question.replyCount]];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.refreshFalg) {
        self.refreshFalg = NO;
        [self.scollView.header beginRefreshing];
    }

    [[NSNotificationCenter defaultCenter] addUniqueObserver:self
                                                   selector:@selector(recvRefreshFalg:)
                                                       name:@"recvRefreshFalg"
                                                     object:nil];

    [[NSNotificationCenter defaultCenter] addUniqueObserver:self
                                                   selector:@selector(recvAppceptAnserAction:)
                                                       name:@"recvAppceptAnswer"
                                                     object:nil];

    [[NSNotificationCenter defaultCenter] addUniqueObserver:self
                                                   selector:@selector(recvViewAnswerImage:)
                                                       name:@"recvViewAnswerImage"
                                                     object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self];


}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)btnFollow:(id)sender {
    //第一步 做登录检查判断
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
        return;
    }
    //登录成功后进行第二步

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    [KVNProgress showWithStatus:@"正在关注,请稍后..."];

    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/uid/payAttent?userId=%ld&fid=%ld", [[UserManager shareUserManager] curUser].userId, (unsigned long) self.question.userId];

    // NSLog(@"urlString:%@",urlString);

    [manager POST:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束刷新
        [self.scollView.header endRefreshing];
        [KVNProgress dismiss];
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"00"]) {
            [sender setHidden:YES];
            [KVNProgress showSuccessWithStatus:[responseObject objectForKey:@"msg"]];
        } else {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
        }
    }     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
        // 结束刷新
        [self.scollView.header endRefreshing];
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"self.questionAnswerPageModel.dataArray.count:%ld", self.questionAnswerPageModel.dataArray.count);
    return self.questionAnswerPageModel.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    QuestionAnswer *questionAnswer = [self.questionAnswerPageModel.dataArray objectAtIndex:[indexPath row]];
    NSString *imageURL = [CommonUtils serializableIdObject:questionAnswer.imageUrl defaultValue:@""];
    NSString *resizeImageURL = [CommonUtils serializableIdObject:questionAnswer.resizedImageUrl defaultValue:@""];


    static NSString *ID = @"QuestionAnswerTableViewCell";

    QuestionAnswerTableViewCell *questionAnswerTableViewCell = [tableView dequeueReusableCellWithIdentifier:ID];

//
//    if (answerTableViewCell == nil) {
//        answerTableViewCell = [[QuestionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//        //将Custom.xib中的所有对象载入
////        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QuestionTableViewCell" owner:nil options:nil];
////        //第一个对象就是CustomCell了
////        answerTableViewCell = [nib objectAtIndex:0];
//    }
//

//    QuestionAnswerTableViewCell *questionAnswerTableViewCell = nil;
//    if (imageURL && imageURL.length != 0) {
//        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QuestionAnswerTableViewCell" owner:nil options:nil];
//        questionAnswerTableViewCell = [nib objectAtIndex:0];
//    } else {
//        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QuestionAnswerNoImageTableViewCell" owner:nil options:nil];
//        questionAnswerTableViewCell = [nib objectAtIndex:0];
//    }
    if (questionAnswerTableViewCell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QuestionAnswerTableViewCell" owner:nil options:nil];
        questionAnswerTableViewCell = [nib objectAtIndex:0];
    }
    questionAnswerTableViewCell.answerId = questionAnswer.answerId;



    //只有问题发布者才能使用采纳
    NSUInteger currLoginedUserId = [[UserManager shareUserManager] curUser].userId;
    if (self.question.userId != currLoginedUserId) {
        [questionAnswerTableViewCell.btnAppcptAnswer setHidden:YES];
    }
    //对自己的回复不能采纳
    if (self.question.userId == currLoginedUserId && questionAnswer.userId == currLoginedUserId) {
        [questionAnswerTableViewCell.btnAppcptAnswer setHidden:YES];
    }
    //如果问题已经解决则无需进行采纳
    if ([self.question.status isEqualToString:@"1"]) {
        [questionAnswerTableViewCell.btnAppcptAnswer setHidden:YES];
    }


    NSString *sex = questionAnswer.sex;
    [questionAnswerTableViewCell.ivSex setHighlighted:NO];
    if ([sex isEqualToString:@"男"]) {
        [questionAnswerTableViewCell.ivSex setImage:[UIImage imageNamed:@"male"]];
    } else if ([sex isEqualToString:@"女"]) {
        [questionAnswerTableViewCell.ivSex setImage:[UIImage imageNamed:@"female"]];
    } else {
        [questionAnswerTableViewCell.ivSex setHighlighted:YES];
    }

    NSString *sign = [CommonUtils serializableIdObject:questionAnswer.slogins defaultValue:@"这家伙很懒,资料都不愿意修改"];

    [questionAnswerTableViewCell.lbSign setText:sign];
    [questionAnswerTableViewCell.lbIdxFloor setText:[NSString stringWithFormat:@"第%ld楼", ([indexPath row] + 1)]];
    [questionAnswerTableViewCell.lbNickName setText:[CommonUtils serializableIdObject:questionAnswer.userName defaultValue:@"昵称"]];
    [questionAnswerTableViewCell.lbAnswerContent setText:[CommonUtils serializableIdObject:questionAnswer.contents defaultValue:@""]];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:SS"];
    NSString *createTime = questionAnswer.createtime;
    @try {
        createTime = [CommonUtils compareCurrentTime:[dateFormat dateFromString:questionAnswer.createtime]];
    }
    @catch (NSException *exception1) {
        NSLog(@"Exception occurred: %@, %@", exception1, [exception1 userInfo]);
    }
    [questionAnswerTableViewCell.lbCreateTime setText:createTime];

    if ([questionAnswer.status isEqualToString:@"0"]) {
        [questionAnswerTableViewCell.btnAcceptStatus setHidden:YES];
    } else {
        [questionAnswerTableViewCell.btnAcceptStatus setHidden:NO];
        [questionAnswerTableViewCell.btnAppcptAnswer setHidden:YES];
    }


    NSString *imageAvatarURL = [CommonUtils serializableIdObject:questionAnswer.userImage defaultValue:@""];
    if (imageAvatarURL && imageAvatarURL.length != 0) {
        [questionAnswerTableViewCell.ivAvatotar setImageWithURL:[NSURL URLWithString:imageAvatarURL] placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];
    }
    if (resizeImageURL && resizeImageURL.length != 0) {
        [questionAnswerTableViewCell.ivAnswerImage setHidden:NO];

        UIImageView *ivAnswerImage = questionAnswerTableViewCell.ivAnswerImage;

        float scaleFactor = questionAnswerTableViewCell.frame.size.width / self.tableView.frame.size.width;
        float frameWidth = ivAnswerImage.frame.size.width / scaleFactor;
        float frmameHeight = (frameWidth * questionAnswer.resizedImageHeight) / questionAnswer.resizedImageWidth;

        questionAnswerTableViewCell.answerImgaeLayoutCConttraint.constant = frmameHeight;

        [self.view setNeedsLayout]; //更新视图
        [self.view layoutIfNeeded];
        
        [questionAnswerTableViewCell.ivAnswerImage setImageWithURL:[NSURL URLWithString:resizeImageURL] placeholderImage:[UIImage imageNamed:@"loading"]];

    } else {
        UIImageView *ivAnswerImage = questionAnswerTableViewCell.ivAnswerImage;
//        questionAnswerTableViewCell.ivAnswerImage.frame = CGRectMake(ivAnswerImage.frame.origin.x, ivAnswerImage.frame.origin.y, 1, 1);
        [questionAnswerTableViewCell.ivAnswerImage setImage:[UIImage imageNamed:@"noImageDataDefault"]];
        questionAnswerTableViewCell.answerImgaeLayoutCConttraint.constant = 1;
        [questionAnswerTableViewCell.ivAnswerImage setHidden:NO];
        [self.view setNeedsLayout]; //更新视图
        [self.view layoutIfNeeded];
    };

    questionAnswerTableViewCell.willViewingImageUrl = imageURL;
    questionAnswerTableViewCell.willViewingResizeImageUrl = resizeImageURL;

    NSString *strRowHeight = [NSString stringWithFormat:@"%f", questionAnswerTableViewCell.bounds.size.height + 1];
    NSString *strRowNo = [NSString stringWithFormat:@"%ld", [indexPath row]];
    [self.rowHeightDictionary setObject:strRowHeight forKey:strRowNo];

    NSLog(@"questionAnswerTableViewCell.height:%f", questionAnswerTableViewCell.bounds.size.height);

    return questionAnswerTableViewCell;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//
//    NSString *strRowNo = [NSString stringWithFormat:@"%ld", [indexPath row]];
//    NSString *strRowHeight = [self.rowHeightDictionary objectForKey:strRowNo];
//
//    return [strRowHeight intValue];
//}

- (IBAction)btnPostAnswerAction:(id)sender {

    //    if ([[self.question status] isEqualToString:@"1"]) {
    //        [KVNProgress showErrorWithStatus:@"该问题已解决,无需再解答"];
    //        return;
    //    }
    
    //第一步 做登录检查判断
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
        return;
    }

    [self performSegueWithIdentifier:@"ToPostAnswerSegue" sender:self];
}

/**
*   处理发布答案请求
*
*  @param sender <#sender description#>
*/
- (IBAction)btnProcessPostAnswerRequestionAction:(id)sender {

}

- (IBAction)btnDeleteQuestionAction:(id)sender {
    //该方法由UIActionSheetDelegate协议定义，在点击ActionSheet的按钮后自动执行
    NSString *string = @"您确定要删除该问题吗?";

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;

    [alert show];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != 0) {
        return;
    }
    // Adds a status below the circle
    [KVNProgress showWithStatus:@"删除中..."];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];


    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/help/delete?Id=%ld&userId=%ld", self.question.questionId, [[UserManager shareUserManager] curUser].userId];


    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
        [KVNProgress dismiss];

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code == nil || ![code isEqualToString:@"00"]) {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            return;
        }

        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            //更新UI操作
        //            [KVNProgress showSuccessWithStatus:@"删除成功" completion:^{
        //
        //            }];
        //        });
        UIViewController *rootViewController = [self.navigationController.viewControllers firstObject];
        if ([rootViewController isKindOfClass:ProfileViewController.class]) {
            ProfileViewController *profileViewController = (ProfileViewController *) rootViewController;
            //更新标识符，让ProfileViewController重新加载数据
            [profileViewController setIsLoadedData:NO];
        }
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //        NSLog(@"Error: %@", error);
        NSLog(@"请求发生异常!!!!!!!!!!!");
        // 结束登陆提示
        //        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //取消上次选择中的被选择效果
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:NO];
}
@end
